package com.jinyi.wwdeng.autodialer

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Application
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import com.jinyi.wwdeng.autodialer.crash.GlobalExceptionHandler
import com.jinyi.wwdeng.autodialer.manager.LoadingManager
import com.jinyi.wwdeng.autodialer.service.KeepAliveService
import com.jinyi.wwdeng.autodialer.utils.CallRecorderUtil
import com.jinyi.wwdeng.autodialer.utils.SPUtils
import com.jinyi.wwdeng.autodialer.utils.event.EventPublisher

class MyApplication : Application() {

    //全局事件发布者
    lateinit var publisher: EventPublisher

    companion object {
        @SuppressLint("StaticFieldLeak")
        lateinit var instance: MyApplication
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
        registerActivityLifecycle()
        publisher = EventPublisher()

        // 初始化全局异常处理器
        GlobalExceptionHandler.getInstance().init(this)
        SPUtils.init(this,"autodialer_data")
        CallRecorderUtil.init()
        startKeepAliveService()
        initLoadingConfig()
    }

    override fun onTerminate() {
        super.onTerminate()
        LoadingManager.getInstance().release()
    }

    /**
     * 启动应用前台服务
     */
    private fun startKeepAliveService(){
        // 启动前台保活服务
//        val intent = Intent(this, KeepAliveService::class.java)
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            startForegroundService(intent)
//        } else {
//            startService(intent)
//        }
    }

    /**
     * 初始化加载中配置
     */
    private fun initLoadingConfig(){
        // 初始化加载管理器配置
        val config = LoadingManager.LoadingConfig()
            .setDefaultMessage(getString(R.string.loading))
            .setCancelable(true)
        LoadingManager.getInstance().initConfig(config)
    }

    /**
     * 注册App生命周期
     */
    private fun registerActivityLifecycle(){
        // 注册Activity生命周期回调
        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            override fun onActivityDestroyed(activity: Activity) {
                // 自动检查并隐藏加载框
                if (LoadingManager.getInstance().isShowing()) {
                    LoadingManager.getInstance().dismiss()
                }
            }
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
            override fun onActivityStarted(activity: Activity) {}
            override fun onActivityResumed(activity: Activity) {}
            override fun onActivityPaused(activity: Activity) {}
            override fun onActivityStopped(activity: Activity) {}
            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
        })
    }
}